//
//  HEGoodSearchViewController.m
//  HealthFamily
//
//  Created by LOOK on 2020/10/25.
//  Copyright © 2020 honglutec. All rights reserved.
//

#import "HEGoodSearchViewController.h"
#import "HEGoodsCell.h"
#import "HEGoodsDetailsViewController.h"
#import "HECategGoodsCell.h"
 
@interface HEGoodSearchViewController ()<UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate>

@property (nonatomic, strong) GDTableView *tableView;
@property (nonatomic, strong) NSMutableArray <HEGoodsModel *> * dataSourceArr;

@property (nonatomic, assign) NSInteger pageNum;
@property (nonatomic, assign) NSInteger pageSize;

@property (nonatomic, strong) QMUITextField *searchTF;


@end

@implementation HEGoodSearchViewController

- (NSMutableArray<HEGoodsModel *> *)dataSourceArr {
    if (!_dataSourceArr) {
        _dataSourceArr = [NSMutableArray array];
    }
    return _dataSourceArr;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    _pageNum = 1;
    _pageSize = 20;
        
    [self initUI];
    
    [self setCustomTableView:self.tableView];
    [self showEmpty];
    
    if ([_keyword isNotBlank]) {
        [self loadData];
    }
}

- (GDTableView *)tableView {
    if (!_tableView) {
        _tableView = [[GDTableView alloc] initWithFrame:CGRectMake(0, ZXNavBarHeight , KScreenWidth, KScreenHeight - ZXNavBarHeight) style:UITableViewStylePlain];
        _tableView.separatorColor = KHexColor(@"EEEEEE");
        _tableView.scrollsToTop = YES;
        _tableView.tableFooterView = [[UIView alloc] init];
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.backgroundColor = KWhiteColor;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        
        __weak __typeof(&*self)weakSelf = self;
        self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{

            weakSelf.isFromHeadRefresh = YES;
            weakSelf.pageNum = 1;
            [weakSelf loadData];
        }];
        
        self.tableView.mj_footer = [MJRefreshAutoFooter footerWithRefreshingBlock:^{
            weakSelf.isFromHeadRefresh = NO;
            weakSelf.pageNum += 1;
            [weakSelf loadData];
        }];
        
        [_tableView registerClass:[HECategGoodsCell class] forCellReuseIdentifier:kCellIdentifier_Right];
    }
    return _tableView;
}

- (void)initUI {
    
    [self.view addSubview:self.tableView];

    // 输入框
    QMUITextField *searchTF = [[QMUITextField alloc] init];
    searchTF.backgroundColor = KHexColor(@"F1F3F8");
    searchTF.layer.cornerRadius = 17;
    searchTF.font = DYFont(16);
    searchTF.placeholder = @"搜索";
    searchTF.placeholderColor = [UIColor colorWithHexString:@"#AAAAAA"];
    searchTF.delegate = self;
    searchTF.text = _keyword;
    _searchTF = searchTF;
    
    UIView *leftWarp = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 49, 18)];
    UIImageView *leftIcon = [[UIImageView alloc] initWithImage:IMAGE_NAMED(@"search")];
    leftIcon.frame = CGRectMake(20, 0, 18, 18);
    [leftWarp addSubview:leftIcon];
    searchTF.leftViewMode = UITextFieldViewModeAlways;
    searchTF.leftView = leftWarp;
 
    UIView *titleWarp = [UIView new];
    [titleWarp addSubview:searchTF];
    [searchTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.centerY.equalTo(titleWarp);
        make.width.mas_offset(KScreenWidth-110);
        make.height.mas_offset(34);
    }];
    [self zx_addCustomTitleView:titleWarp];
 

    [self zx_setRightBtnWithText:@"搜索" clickedBlock:^(UIButton * _Nonnull btn) {
        
        [self.tableView.mj_header beginRefreshing];
    }];
    self.zx_navRightBtn.zx_tintColor = KHexColor(@"888888");
}

#pragma mark -

- (void)loadData {
    
    if (![_keyword isNotBlank]) {
        [Dialog toastBottom:@"请输入搜索内容~"];
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        return;
    }
    
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setValue:[NSNumber numberWithInteger:_pageNum] forKey:@"pageNum"];
    [dict setValue:[NSNumber numberWithInteger:_pageSize] forKey:@"pageSize"];
    [dict setValue:_keyword forKey:@"keyword"];

    [WOAFNetWorkingHandle GETWithBaseUrl:KServerUrl suffixUrl:KGoodsList parameters:dict success:^(id  _Nonnull responseObject) {
        
        if (self.isFromHeadRefresh) {
            [self.dataSourceArr removeAllObjects];
        }
        
        HEMallPageResponse *response = [HEMallPageResponse mj_objectWithKeyValues:responseObject];
        [self.dataSourceArr addObjectsFromArray:[HEGoodsModel mj_objectArrayWithKeyValuesArray:response.data.records]];
        [self.tableView reloadData];
        
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];

        if (self.dataSourceArr.count == 0) {
            [self showEmpty];
        }else {
            if (response.data.records.count == 0) {
                [Dialog toastBottom:@"没有更多数据了~"];
            }
        }

    } failure:^(NSError * _Nonnull error) {
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
    }];
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _dataSourceArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    HECategGoodsCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellIdentifier_Right];
    cell.model = _dataSourceArr[indexPath.row];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return [tableView fd_heightForCellWithIdentifier: kCellIdentifier_Right cacheByIndexPath:indexPath configuration:^(HECategGoodsCell *cell) {
        cell.model = self.dataSourceArr[indexPath.row];
    }];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    HEGoodsModel *model = _dataSourceArr[indexPath.row];
    HEGoodsDetailsViewController *vc = [HEGoodsDetailsViewController new];
    vc.goodsId = model.id;
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark -
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {

    NSString *text = [textField.text stringByReplacingCharactersInRange:range withString:string];
    _keyword = text;
    return YES;
}


@end
